package itu.twitterandro.application;


import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AuthActivity extends Activity {
	private Twitter twitter;
	private OAuthProvider provider;
	private CommonsHttpOAuthConsumer consumer;

	private String CONSUMER_KEY  = TwitterKeys.CONSUMER_KEY;
	private String CONSUMER_SECRET = TwitterKeys.CONSUMER_SECRET;
	private String CALLBACK_URL = "callback://tandroit";
	
	private Button buttonLogin;
	
	
	public void onCreate(Bundle savedInstanceState) {
		System.setProperty("http.keepAlive", "false");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainauth);
		
		// checking saved login
		isUserLoggedIn();
		
		// setting consumer provider on the Application service
		getConsumerProvider();
		
		// Defined login button and listener
		buttonLogin = (Button)findViewById(R.id.ButtonLogin);
		buttonLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				oAuthReq();
			}
		});
	}
	
	private void oAuthReq() {
		try {
			consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
			provider = new DefaultOAuthProvider(TwitterKeys.REQUEST_TOKEN,
					TwitterKeys.ACCESS_TOKEN, TwitterKeys.AUTHORIZE);
			String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
			Toast.makeText(this, "Please authoize this app!", Toast.LENGTH_LONG).show();
			setConsumerProvider();
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
		} catch(Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	
	// After the authentication
	protected void onResume() {
		super.onResume();
		if(this.getIntent() != null && this.getIntent().getData() != null) {
			Uri uri = this.getIntent().getData();
			if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
				String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
				try {
					// this will populate token and token_secret in consumer
					provider.retrieveAccessToken(consumer, verifier);
					
					// Get Access Token and persist it
					AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
					storeAccessToken(a);
					
					// initialize Twitter4J
					twitter = new TwitterFactory().getInstance();
					twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
					twitter.setOAuthAccessToken(a);
					((TwitterApplication)getApplication()).setTwitter(twitter);
					
					startFirstActivity();
				} catch(Exception e) {
					//Log.e(APP, e.getMessage());
					e.printStackTrace();
					Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
				}
			}
		}
	}
	
	/**
	 * This method persists the Access Token information so that a user
	 * is not required to re-login every time the app is used
	 * 
	 * @param a - the access token
	 */
	private void storeAccessToken(AccessToken a) {
		SharedPreferences settings = getSharedPreferences(TwitterKeys.PREFS_NAME, MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("accessTokenToken", a.getToken());
		editor.putString("accessTokenSecret", a.getTokenSecret());
		editor.commit();
	}
	
	private void isUserLoggedIn() {
		// Getting acceess token
		AccessToken accToken = getAccessToken();
		if(accToken == null) return; 	// if there is no credentials 
        								//return authentication activity
		
		// initialize Twitter4j
		twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
		twitter.setOAuthAccessToken(accToken);
		((TwitterApplication)getApplication()).setTwitter(twitter);
		
		startFirstActivity();
		finish();
	}
	
	////////////////////////
	// Start the activity //
	////////////////////////
	private void startFirstActivity() {
		Intent intent = new Intent(this, TwitterAndroActivity.class);
		startActivityForResult(intent, TwitterMenus.ACTIVITY_TIMELINE_TWEETS);
	}
	
	/**
	 * This method checks the shared prefs to see if we have persisted a user token/secret
	 * if it has then it logs on using them, otherwise return null
	 * 
	 * @return AccessToken from persisted prefs
	 */
	private AccessToken getAccessToken() {
		SharedPreferences settings = getSharedPreferences(TwitterKeys.PREFS_NAME, MODE_PRIVATE);
		String token = settings.getString("accessTokenToken", "");
		String tokenSecret = settings.getString("accessTokenSecret", "");
		if (token!=null && tokenSecret!=null && !"".equals(tokenSecret) && !"".equals(token)){
			return new AccessToken(token, tokenSecret);
		}
		return null;
	}
	
	/**
	 * Get the consumer and provider from the 
	 * application service (in the case that the
	 * activity is restarted so the objects are not lost)
	 */
	private void getConsumerProvider() {
		OAuthProvider p = ((TwitterApplication)getApplication()).getProvider();
		if (p!=null){
			provider = p;
		}
		CommonsHttpOAuthConsumer c = ((TwitterApplication)getApplication()).getConsumer();
		if (c!=null){
			consumer = c;
		}
	}
	
	/**
	 * Set the consumer and provider from the application service (in the case that the
	 * activity is restarted so the objects are not lost)
	 */
	private void setConsumerProvider() {
		if (provider!=null){
			((TwitterApplication)getApplication()).setProvider(provider);
		}
		if (consumer!=null){
			((TwitterApplication)getApplication()).setConsumer(consumer);
		}
	}

}
